package it.uniroma3.dia.ia.textcategorization.datasource.odpdump;

import it.uniroma3.dia.ia.textcategorization.datasource.DataSourceException;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

final class SubcategoriesFinder {

	static Set<String> getSubcategoriesNamesFor(String path) {
		Set<String> subcategoriesNames = null;
		
		SubcategoriesFinderHandler handler = new SubcategoriesFinderHandler(
				path);
		try {
			XMLReader reader = XMLReaderFactory.createXMLReader();
			reader.setContentHandler(handler);
			reader.parse(ODPDumpLocations.STRUCTURE);
		} catch (SAXException exception) {
			if (handler.subcategoriesFound()) {
				subcategoriesNames = handler.getSubcategoriesNames();
			} else {
				throw new DataSourceException(
						"Exception while trying to parse the dump's structure.",
						exception);
			}
		} catch (IOException exception) {
			throw new DataSourceException(
					"Exception while trying to access the dump's structure.",
					exception);
		}

		subcategoriesNames = removePrefix(subcategoriesNames, path);
		return subcategoriesNames;
	}

	static private Set<String> removePrefix(
			Set<String> prefixedSubcategoriesNames, String prefix) {
		Set<String> subcategoriesNames = new HashSet<String>();
		for (String prefixedSubcategoryName : prefixedSubcategoriesNames) {
			String subcategoryName = prefixedSubcategoryName.substring(prefix
					.length() + 1);
			subcategoriesNames.add(subcategoryName);
		}
		return subcategoriesNames;
	}

}
